package com.ww.learn.coroutine.context

import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

// 打印结果
//[Ctx1 @coroutine#1] Started in ctx1
//[Ctx2 @coroutine#1] Working in ctx2
//[Ctx1 @coroutine#1] Finished in ctx1

/**
 * 注意：不再需要某个newSingleThreadContext中创建的线程的时候，使用了Kotlin标准库中的use函数来释放该线程
 */
fun main() {
    newSingleThreadContext("Ctx1").use { ctx1 ->
        newSingleThreadContext("Ctx2").use { ctx2 ->
            runBlocking(ctx1) {
                log("Started in ctx1")
                withContext(ctx2) {
                    log("Working in ctx2")
                }
                log("Finished in ctx1")
            }
        }
    }
}